package by.ostrovsky.webhousingsystem.bean;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.hibernate.entity.common.Common;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public abstract class TemplateDataBean<T extends Common<Long>> extends
		ActionSupport implements SessionAware {
	private static Logger logger = Logger.getLogger(TemplateDataBean.class);
	protected List<T> entityList = null;
	protected List<T> selectedEntities = null;
	protected String[] selectedEllements = null;
	protected String[] id = null;
	protected SessionMap<String, Object> sessionMap;

	@Override
	public void setSession(Map<String, Object> arg0) {
		this.sessionMap = (SessionMap<String, Object>) arg0;
	}

	@Override
	public abstract String execute() throws Exception;

	public void next() {
		initSelected();
	}

	public List<T> getEntityList() {
		return entityList;
	}

	public void setEntityList(List<T> employeList) {
		this.entityList = employeList;
	}

	public List<T> getSelectedEntities() {
		return selectedEntities;
	}

	public void setSelectedEntities(List<T> selectedEntities) {
		this.selectedEntities = selectedEntities;
	}

	public void deleteRecord() throws CommonException {
		entityList.removeAll(selectedEntities);
		delete();
	}

	public String[] getSelectedEllements() {
		return selectedEllements;
	}

	public void setSelectedEllements(String[] selectedEllements) {
		this.selectedEllements = selectedEllements;
	}

	public abstract void delete() throws CommonException;

	public abstract void update() throws CommonException;

	public abstract void read() throws CommonException;

	public void initSelected() {
		selectedEntities = new LinkedList<T>();
		Boolean match;
		try {
			for (String str : selectedEllements) {
				for (T entity : entityList) {
					match = id[Integer.parseInt(str)-2].equals(entity.getId()
							.toString());
					if (match) {
						selectedEntities.add(entity);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}

	protected void clearSelectedEllements() {
		selectedEllements = new String[0];
	}

	public String[] getId() {
		return id;
	}

	public void setId(String[] id) {
		this.id = id;
	}
}